package org.exam.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.exam.system.domain.Employee;
import org.exam.system.domain.Role;
import org.exam.system.mapper.EmployeeMapper;
import org.exam.system.query.EmployeeQuery;
import org.exam.system.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void add(Employee employee) {
        employeeMapper.add(employee);
        List<Long> roles = employee.getRoles();
        if (roles.size() > 0) {
            employeeMapper.addEmployeeRole(employee);
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        employeeMapper.deleteRoleByEmployeeId(id);
        employeeMapper.delete(id);
        //条件删除
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.get(id);
    }

    @Override
    public List<Employee> getAll() {
        return employeeMapper.getAll();
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        employeeMapper.update(employee);
        employeeMapper.deleteRoleByEmployeeId(employee.getId());
        List<Long> roles = employee.getRoles();
        if (roles.size() > 0) {
            employeeMapper.addEmployeeRole(employee);

            //MongoDB修改
        }
    }

    @Override
    public void patchDelete(Long[] ids) {
        for (Long id : ids) {
            employeeMapper.deleteRoleByEmployeeId(id);
        }
        employeeMapper.patchDelete(ids);
    }

    @Override
//    分页
    public PageInfo<Employee> queryPage(EmployeeQuery employeeQuery) {
        PageHelper.startPage(employeeQuery.getCurrentPage(), employeeQuery.getPageSize());
        List<Employee> data = employeeMapper.queryPage(employeeQuery);
//===========================================================================================================
        for (Employee datum : data) {

            List<Role> roles = employeeMapper.findRoleByEmployeeId(datum.getId());
            datum.setDbRoles(roles);
        }
        return new PageInfo<>(data);
    }
}
